import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:openchina/common/event_bus.dart';
import 'package:openchina/constants/constants.dart' show AppUrls, AppInfo;
import 'package:openchina/pages/login_web_page.dart';
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';
import 'package:openchina/widgets/NewsListItem.dart';
import 'package:flutter/cupertino.dart';

class NewListPage extends StatefulWidget {
  @override
  _NewListPageState createState() => _NewListPageState();
}

class _NewListPageState extends State<NewListPage> {
  bool isLogin = false;
  int curPage = 1;
  List newsList;
  bool isLoadMore = false;
  ScrollController _scrollController = ScrollController();
  bool hasMore = false;
  String bottomNotices = "加载更多";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixels = _scrollController.position.pixels;
      if (maxScroll == pixels) {
//        curPage++;
        _getNewsList(true);
      }
    });
    DataUtil.isLogin().then((isLogin) {
      if (!mounted) return;
      setState(() {
        this.isLogin = isLogin;
        if (this.isLogin) {
          _getNewsList(false);
        }
      });
    });
    eventBus.on<LoginEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = true;
      });
      _getNewsList(false);
    });
    eventBus.on<LogoutEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = false;
      });
    });
  }

  _getNewsList(isLoadMore) async {
    DataUtil.isLogin().then((isLogin) {
      if (isLogin) {
        DataUtil.getTokenAccess().then((accessToken) {
          if (accessToken != null && accessToken.length != 0) {
            Map<String, dynamic> params = new Map<String, dynamic>();
            params['access_token'] = accessToken;
            params['catalog'] = 1;
            params['page'] = curPage;
            params['pageSize'] = 10;
            params['dataType'] = AppInfo.JSON;
            NetUtil.get(AppUrls.NEWS_LIST, params).then((data) {
              print('新闻列表 $data');
              if (data != null && data.isNotEmpty) {
//                {"newslist":[{"author":"贝克街的天才","id":110756,"title":"Mars-java 2.2.2 发布，不需要容器的 Java Web 开发框架","type":4,"authorid":1248232,"pubDate":"2019-10-22 12:36:08","commentCount":6},{"author":"kaka996","id":110755,"title":"跨平台应用商店 Dapps 1.0.3 发布，增加 12306 抢票等多个应用","type":4,"authorid":3305311,"pubDate":"2019-10-22 10:11:31","commentCount":0},{"author":"若依开源","id":110754,"title":"若依后台管理系统 4.1 发布，新增多项功能 ","type":4,"authorid":1438828,"pubDate":"2019-10-22 09:52:24","commentCount":5},{"author":"mrbird","id":110753,"title":"FEBS Cloud 微服务权限系统 1.3 版本发布","type":4,"authorid":3690073,"pubDate":"2019-10-22 09:02:26","commentCount":2},{"author":"顾钧","id":110752,"title":"Milvus 0.5.0 发布，新增 Java SDK","type":4,"authorid":4209276,"pubDate":"2019-10-22 08:59:06","commentCount":1},{"author":"nobodyiam","id":110751,"title":"Apollo 1.5.0 发布，开源分布式配置中心"
                Map<String, dynamic> map = json.decode(data);
                List _newsList = map['newslist'];
                if (_newsList != null && _newsList.length > 0) {
                  setState(() {
                    hasMore = true;
                    bottomNotices = '加载更多';
                  });
                  curPage++;
                } else {
                  setState(() {
                    hasMore = false;
                    bottomNotices = '没有更多数据了';
                  });
                }
                if (!mounted) return;
                setState(() {
                  if (isLoadMore) {
                    newsList.addAll(_newsList);
                  } else {
                    newsList = _newsList;
                  }
                });
              } else {
                setState(() {
                  hasMore = false;
                  bottomNotices = '没有更多数据了';
                });
              }
            });
          }
        });
      }
    });
  }

  Future _login(BuildContext context) async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => LoginWebPage(),
      ),
    );
    if (result != null && result == 'refresh') {
      //跳转过去后下一个界面约定子弹表示登录成功
      eventBus.fire(LoginEvent()); //登录成功通知loginEvent
    }
  }

  Future<Null> _pullToRefresh() async {
    curPage = 1;
    _getNewsList(false);
    return null;
  }

  @override
  Widget build(BuildContext context) {
    if (!this.isLogin) {
      return Center(
        child: Column(
          children: <Widget>[
            Text('部分限制需登录才能查看'),
            InkWell(
              onTap: () async {
                await _login(context);
              },
              child: Text('登录'),
            )
          ],
        ),
      );
    }
    return RefreshIndicator(child: buildListView(), onRefresh: _pullToRefresh);
  }

  Widget buildListView() {
    if (newsList == null) {
      _getNewsList(false);
      return CupertinoActivityIndicator();
    }
    return ListView.builder(
        controller: _scrollController,
        itemCount: newsList.length + 1,
        itemBuilder: (context, index) {
          if (index == newsList.length) {
            if (hasMore) {
              return build_has_more_container();
            } else {
              return build_no_more_container();
            }
          }
          //TODO
          return NewsListItem(
            newsList: newsList[index],
          );
        });
  }

  Widget build_no_more_container() {
    return Container(
      alignment: Alignment.center,
      height: 40.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 10.0,
          ),
          Text(bottomNotices),
        ],
      ),
    );
  }

  Widget build_has_more_container() {
    return Container(
      alignment: Alignment.center,
      height: 40.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CupertinoActivityIndicator(),
          SizedBox(
            height: 10.0,
          ),
          Text(bottomNotices),
        ],
      ),
    );
  }
}
